package bll

import (
	"context"

	"manager/event"
	"manager/model"
	"manager/model/entity"
	"manager/store"
	"manager/store/postgres"
	"time"
)

type region struct {
	iRegion store.IRegion
}

var Region = &region{
	iRegion: postgres.Region,
}

func (a *region) init() func() {
	return func() {}
}

func (a *region) onEvent(*event.Data) {}

// Create 创建
func (a *region) Create(ctx context.Context, in *model.RegionCreateRequest) error {
	var (
		err error
	)

	// 构建创建现场数据
	c := buildRegion(in)
	_, err = a.iRegion.Create(ctx, c)
	return err
}

// Update 更新
func (a *region) Update(ctx context.Context, in *model.RegionUpdateRequest) error {
	var (
		dict = make(map[string]interface{})
	)

	// 批量更新上级区域
	if len(in.Codes) > 0 {
		postgres.GetDB(ctx).Model(&entity.Region{}).Where("code in ?", in.Codes).UpdateColumn("upper_region", in.UpperRegion)
		return nil
	}

	updateAt := time.Now().Unix()
	in.UpdatedAt = &updateAt

	if in.Code != nil {
		dict["code"] = in.Code
	}

	if in.CountryCode != nil {
		dict["country_code"] = in.CountryCode
	}

	if in.RegionNameE != nil {
		dict["region_name_e"] = in.RegionNameE
	}

	if in.RegionNameC != nil {
		dict["region_name_c"] = in.RegionNameC
	}

	if in.Level != nil {
		dict["level"] = in.Level
	}

	if in.UpperRegion != nil {
		dict["upper_region"] = in.UpperRegion
	}

	if in.UpdatedAt != nil {
		dict["updated_at"] = in.UpdatedAt
	}

	// do other update here

	return a.iRegion.Update(ctx, in.Id, dict)
}

// Delete 删除
func (a *region) Delete(ctx context.Context, in *model.RegionDeleteRequest) error {
	return a.iRegion.Delete(ctx, in.Id)
}

// List 列表查询
func (a *region) List(ctx context.Context, in *model.RegionListRequest) (*model.RegionListResponse, error) {
	var (
		err   error
		total int
		list  []*entity.Region
		out   = &model.RegionListResponse{}
	)

	if total, list, err = a.iRegion.List(ctx, in); err != nil {
		return nil, err
	}

	out.Total = total
	out.List = model.RegionsEntityToDto(list)

	return out, nil
}

// Find 列表查询
func (a *region) Find(ctx context.Context, in *model.RegionInfoRequest) (*model.RegionInfo, error) {
	var (
		err  error
		data *entity.Region
		out  = &model.RegionInfo{}
	)

	if data, err = a.iRegion.Find(ctx, in); err != nil {
		return nil, err
	}

	out = model.RegionEntityToDto(data)
	return out, nil
}

// buildRegion 构建创建数据现场
func buildRegion(in *model.RegionCreateRequest) *entity.Region {
	// todo: check the entity is required
	return &entity.Region{

		Code: in.Code,

		CountryCode: in.CountryCode,

		RegionNameE: in.RegionNameE,

		RegionNameC: in.RegionNameC,

		Level: in.Level,

		UpperRegion: in.UpperRegion,

		CreatedAt: time.Now().Unix(),

		UpdatedAt: time.Now().Unix(),
	}
}
